﻿using System.Web;
using NHibernate;
namespace Kratos.Framework.Repositories.NHibernateProvider
{
    public interface ISessionManager
    {
        ISession Get();
        void Set(ISession value);
        void Unload();
    }

    public class SessionManager : ISessionManager
    {
        private readonly ISessionFactory _sessionFactory;

        public SessionManager(ISessionFactory sessionFactory)
        {
            _sessionFactory = sessionFactory;
        }

        public ISession Get()
        {
            var session = HttpContext.Current.Items["KratosSession"] as ISession;
            if (session == null)
            {
                session = _sessionFactory.OpenSession();
                Set(session);
            }

            return session;
        }

        public void Set(ISession session)
        {
            if (session != null)
                HttpContext.Current.Items.Add("KratosSession", session);
        }

        public void Unload()
        {
            if (!HttpContext.Current.Items.Contains("KratosSession")) return;
            var session = HttpContext.Current.Items["KratosSession"] as ISession;
            session.Dispose();
            HttpContext.Current.Items.Remove("KratosSession");
        }
    }
}
